package org.web.common.sso.server.biz;

import lombok.Setter;
import org.springframework.stereotype.Service;
import org.web.base.domain.ResultDO;
import org.web.base.domain.exception.ResultMessageEnum;
import org.web.base.domain.helper.ResultHelper;
import org.web.base.helper.EnumHelper;
import org.web.common.sso.server.config.SSOServerConfig;
import org.web.common.sso.server.controller.info.SsoMessageInfoEnum;
import org.web.common.sso.server.domain.SsoTokenDO;
import org.web.common.sso.server.helper.redis.CacheSessionDO;
import org.web.common.sso.server.query.QuerySsoToken;
import org.web.common.sso.server.service.SsoTokenService;

import javax.annotation.Resource;

@Service("databaseTokenBiz")
public class DatabaseTokenBizImpl extends AbstractTokenBiz {

    @Resource
    private SSOServerConfig ssoServerConfig;

    @Resource
    private SsoTokenService ssoTokenService;

    @Override
    public ResultDO<CacheSessionDO> exchangeToken(String token) {
        QuerySsoToken querySsoToken = new QuerySsoToken();
        querySsoToken.setSsoToken(token);
        SsoTokenDO ssoTokenDO = ssoTokenService.selectOneSsoToken(querySsoToken);
        ResultDO<CacheSessionDO> resultDO = new ResultDO();
        if (System.currentTimeMillis() > ssoTokenDO.getExpireTime()) {
            ResultHelper.buildResultDOByResultMessageEnum(resultDO, ResultMessageEnum.DATA_LOSE_EFFICACY, SsoMessageInfoEnum.getSessionByToken_db_lose_efficacy.getMessage(), null);
            SsoTokenDO updateSsoTokenDO = new SsoTokenDO();
            updateSsoTokenDO.setSsoTokenId(ssoTokenDO.getSsoTokenId());
            updateSsoTokenDO.setIsDelete(EnumHelper.DELETE.Y.name());
            ssoTokenService.updateSsoTokenBySsoTokenId(updateSsoTokenDO);
            return resultDO;
        }

        CacheSessionDO cacheSessionDO = new CacheSessionDO();
        cacheSessionDO.setAccountNum(ssoTokenDO.getAccountNum());
        cacheSessionDO.setAccountName(ssoTokenDO.getAccountName());
        cacheSessionDO.setLastMarkTime(ssoTokenDO.getUpdateTime().getTime());
        resultDO.setDomain(cacheSessionDO);
        return resultDO;
    }

    @Override
    public void refreshToken(String token, CacheSessionDO cacheSessionDO) {
        QuerySsoToken querySsoToken = new QuerySsoToken();
        querySsoToken.setSsoToken(token);
        SsoTokenDO ssoTokenDO = ssoTokenService.selectOneSsoToken(querySsoToken);
        ssoTokenDO.setExpireTime(System.currentTimeMillis() + ssoServerConfig.getInCashTime() * ONE_MINUTE_THOUSANDTH);
        ssoTokenService.updateSsoTokenBySsoTokenId(ssoTokenDO);
    }
}
